import { Table, Input , Col, Row, Button ,Tree,DatePicker ,message, Modal,Select,Space,Menu } from 'antd';
const { Search } = Input;
import React, { useState, useEffect} from 'react';
import { EditableProTable } from '@ant-design/pro-table';
import { DownOutlined,PaperClipOutlined,SearchOutlined} from '@ant-design/icons';

import { numberConversion } from '@/utils/utils';

import { reportByDevice ,queryDevicelistAndSet } from '@/services/energyAnalysis';

import styles from './style.less'
import moment from 'moment'
const { Option } = Select;

const Report: React.FC = () => {





  const cs = [
    {
      title: '时间',
      dataIndex: 'time',
      key: 'time',
      width: 70,
      fixed: 'left',
      
    }
  ];
const [selectData, setSelectData] = useState();
const [columns, setColumns] = useState(cs);
const [type, setType] = useState('date');
const [cdate, setCdate] = useState(moment());
const [loading, setLoading] = useState<boolean>(true);
const [xwidth, setXwidth] = useState(1000);


useEffect(() => {
  setAnalysisData(cdate,type);
}, [type,cdate])
  

useEffect(() => {
  setDevice();
}, [])


  const setDevice = async () => {
    let resultData = await queryDevicelistAndSet({ });
   
    let deviceList =resultData.list;
    let multiplier=resultData.multiplier||4000;
    let conversion=resultData.conversion||0.1229;
    if(columns.length==1){
      let newColumns=[...columns];
    
      for(let i=0;i<deviceList.length;i++){
        let sub=deviceList[i]?.deviceId;
        newColumns.push( {
          title: deviceList[i]?.deviceName,
          children: [
            {
              title: '总电能',
              dataIndex: 'valuea'+sub,
              key: 'valuea'+sub,
              render: (text, _,record) => 
              <>{numberConversion(text*multiplier)} </>
            
            },
            {
              title: '本期折标',
              dataIndex: 'valuea'+sub,
              render: (text, _,record) => 
               <>{numberConversion(text*multiplier*conversion)}</>
            }, 
            {
              title: '有功',
              dataIndex: 'valueb'+sub,
              key: 'valueb'+sub,
         
            
            },
            {
              title: '无功',
              dataIndex: 'valuec'+sub,
              key: 'valuec'+sub,
             
            
            },
            {
              title: '功率因素',
              dataIndex: 'valued'+sub,
              key: 'valued'+sub,
             
            
            },
          ],
        },)
      }
      setColumns(newColumns);
      setXwidth(deviceList.length*460)
  }
}

  const setAnalysisData = async (pdate,ptype) => {
    let date=formatTime(pdate);
    const analysis = await reportByDevice({type:ptype,date:pdate==null?null:date});
    setSelectData(analysis);
    setLoading(false);
   }

    function PickerWithType({ type, onChange }) {
      if (type === 'date') return <DatePicker  value={cdate}  popupStyle={{ background: 'rgb(20, 49, 115)'}}   bordered={false}  onChange={onChange} />;
      return <DatePicker  value={cdate} popupStyle={{ background: 'rgb(20, 49, 115)'}}     bordered={false}  picker={type} onChange={onChange} />;
    }


    const ToExport = async () => {
      const hide = message.loading('导出中');
      try {
       
        window.location.href="/api/energy/reportByDevice/export?type="+type+"&date=" +formatTime(cdate);
        return true;
      } catch (error) {
        hide();
        message.error('导出失败请重试！');
        return false;
      }
    };
    

    const  formatTime = (pdate) => {
      let date=moment(pdate).format("YYYY-MM-DD");
      if(type=="week"){
        date= moment(pdate).startOf('week').format('YYYY-MM-DD');
      }else if(type=="month"){
        date= moment(pdate).startOf('month').format('YYYY-MM-DD');
      }else if(type=="quarter"){
        date= moment(pdate).startOf('quarter').format('YYYY-MM-DD');
      }else if(type=="year"){
        date= moment(pdate).startOf('year').format('YYYY-MM-DD');
      }
      return  date;
    }


   
    function SwitchablePicker() {
     
      return (
        <Space>
          <div  className={styles.inputBg} >
            <Select value={type}  bordered={false}    dropdownStyle={{ background: 'rgb(20, 49, 115)'}}  onChange={setType}>
                <Option value="date">日</Option>
                <Option value="week">周</Option>
                <Option value="month">月</Option>
                <Option value="quarter">季度</Option>
                <Option value="year">年</Option>
            </Select>
          </div>
          <div  className={styles.inputBg} >
            <PickerWithType type={type} onChange={value =>{ setCdate(value)}} />
          </div>(kw·h)
        </Space>
      );
    }
    return (
      <div  className={styles.main}>
            <Row className={styles.tabletop}>
           
              <SwitchablePicker />
              <Button className={styles.exporttBtn}  onClick={()=>ToExport()}
              type="primary" >
              <PaperClipOutlined />
              导出
            </Button> 
            </Row>
            <Table 
             columns={columns}
             scroll={{ x: xwidth }} 
             loading={loading}
             rowKey="time"  dataSource={selectData}   pagination={{ position: ['none','none'] , pageSize: 31}} > 
             

              
           </Table>
 
    
  </div>
    );
};

export default Report;